import { GetUrl } from '@/common/decorator/apiurl.decorator';
import { Serialize } from '@/common/decorator/serialize.decorator';
import { SearchDto } from '@/common/dto/base-search.dto';
import { IdsDto } from '@/common/dto/ids.dto';
import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Put,
  Query,
  Req,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Request } from 'express';
import { SysUser } from '../users/entities/user.entity';
import { CreateMenuDto } from './dto/create-menu.dto';
import { ResultMenuConverterDto } from './dto/result-converter.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { MenusService } from './menus.service';
import { CacheResponse } from '@/common/decorator/cache.decorator';

@Controller('menus')
@ApiTags('菜单管理')
export class MenusController {
  constructor(private readonly menusService: MenusService) {}

  @Post()
  @ApiOperation({ summary: '创建菜单' })
  @Serialize(ResultMenuConverterDto, false)
  create(@Body() body: CreateMenuDto) {
    return this.menusService.create(body);
  }

  @Get()
  @ApiOperation({ summary: '列表查询菜单' })
  findAll(@Query() query: SearchDto) {
    return this.menusService.findAllList(query);
  }

  @Get(':id/form')
  @CacheResponse(30) // 缓存5分钟
  @ApiOperation({ summary: '根据ID菜单' })
  // 最好单独写针对性进行配置，直接用SysMenu模型不推荐
  @Serialize(ResultMenuConverterDto, false)
  async findOne(@Param('id') id: string, @GetUrl() _url: string) {
    // console.log('🚀 ~ 自定义参数装饰器 ~ url:', url);
    return await this.menusService.findOne(id);
  }

  @Put(':id')
  // @CacheResponse(30)
  @ApiOperation({ summary: '编辑菜单' })
  update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateMenuDto: UpdateMenuDto,
  ) {
    return this.menusService.update(id, updateMenuDto);
  }

  @Delete(':ids')
  @ApiOperation({ summary: '根据ID删除菜单' })
  remove(@Param() ids: IdsDto) {
    return this.menusService.remove(ids);
  }

  @Patch(':id')
  @ApiOperation({ summary: '修改菜单状态' })
  updateStatus(
    @Param('id', ParseIntPipe) id: number,
    @Query() query: UpdateMenuDto,
  ) {
    return this.menusService.updateStatus(id, query);
  }

  @Get('routes')
  @ApiOperation({ summary: '构建路由' })
  buildRoutesByMenu(@Req() req: Request) {
    const { roleIds } = req.user as SysUser;
    return this.menusService.buildRoutesByMenu(roleIds, false);
  }

  @Get('options')
  @ApiOperation({ summary: '菜单树角色选择' })
  buildTreeByMenu() {
    return this.menusService.buildTreeByMenu();
  }
}
